import { useCallback, useState } from 'react'
import { useDropzone } from 'react-dropzone'
import { toast } from 'react-toastify'
import { useStore } from '../store/useStore'
import { generate3DModel, generate3DModelFromMultiImages, checkGenerationStatus, checkMultiImageGenerationStatus } from '../services/api'
import PaymentRequiredModal from './PaymentRequiredModal'
import GenerationSettings from './GenerationSettings'

export default function ImageUploader() {
  const { 
    uploadedImage,
    setUploadedImage, 
    setGenerating, 
    setGenerationProgress,
    setModelData,
    setCurrentStep,
    isGenerating,
    generationProgress
  } = useStore()
  
  const [uploadStatus, setUploadStatus] = useState('')
  const [showPaymentModal, setShowPaymentModal] = useState(false)
  const [generationMode, setGenerationMode] = useState('single') // 'single' or 'multi'
  const [multiImages, setMultiImages] = useState([]) // 存储多张图片
  const [generationSettings, setGenerationSettings] = useState(null) // 生成设置

  // 单图上传
  const onDropSingle = useCallback((acceptedFiles) => {
    const file = acceptedFiles[0]
    
    if (!file) {
      toast.error('请选择有效的图片文件')
      return
    }

    // 验证文件大小（限制10MB）
    if (file.size > 10 * 1024 * 1024) {
      toast.error('图片大小不能超过10MB')
      return
    }

    // 读取图片预览
    const reader = new FileReader()
    reader.onload = (e) => {
      setUploadedImage(e.target.result, file)
      toast.success('✅ 图片上传成功！点击下方按钮生成 3D 模型', {
        autoClose: 4000,
        icon: "📸"
      })
    }
    reader.readAsDataURL(file)
  }, [setUploadedImage])

  // 多图上传
  const onDropMulti = useCallback((acceptedFiles) => {
    if (acceptedFiles.length === 0) {
      toast.error('请选择有效的图片文件')
      return
    }

    // 验证文件数量
    if (multiImages.length + acceptedFiles.length > 4) {
      toast.error('最多只能上传4张图片')
      return
    }

    // 验证每个文件大小
    for (const file of acceptedFiles) {
      if (file.size > 10 * 1024 * 1024) {
        toast.error(`图片 ${file.name} 大小超过10MB`)
        return
      }
    }

    // 读取所有图片预览
    const newImages = []
    let loadedCount = 0

    acceptedFiles.forEach((file, index) => {
      const reader = new FileReader()
      reader.onload = (e) => {
        newImages.push({
          preview: e.target.result,
          file: file,
          id: Date.now() + index
        })
        
        loadedCount++
        if (loadedCount === acceptedFiles.length) {
          setMultiImages(prev => [...prev, ...newImages])
          toast.success(`✅ 已上传 ${acceptedFiles.length} 张图片 (${multiImages.length + acceptedFiles.length}/4)`, {
            autoClose: 3000,
            icon: "📸"
          })
        }
      }
      reader.readAsDataURL(file)
    })
  }, [multiImages])

  // 单图模式的dropzone
  const { 
    getRootProps: getRootPropsSingle, 
    getInputProps: getInputPropsSingle, 
    isDragActive: isDragActiveSingle 
  } = useDropzone({
    onDrop: onDropSingle,
    accept: {
      'image/*': ['.jpeg', '.jpg', '.png', '.webp']
    },
    maxFiles: 1,
    multiple: false,
    disabled: generationMode !== 'single'
  })

  // 多图模式的dropzone
  const { 
    getRootProps: getRootPropsMulti, 
    getInputProps: getInputPropsMulti, 
    isDragActive: isDragActiveMulti 
  } = useDropzone({
    onDrop: onDropMulti,
    accept: {
      'image/*': ['.jpeg', '.jpg', '.png', '.webp']
    },
    maxFiles: 4,
    multiple: true,
    disabled: generationMode !== 'multi' || multiImages.length >= 4
  })

  // 删除多图中的某张图片
  const removeMultiImage = (imageId) => {
    setMultiImages(prev => prev.filter(img => img.id !== imageId))
    toast.info('图片已移除')
  }

  // 切换生成模式
  const switchMode = (mode) => {
    if (isGenerating) {
      toast.warning('正在生成中，无法切换模式')
      return
    }
    
    setGenerationMode(mode)
    if (mode === 'single') {
      setMultiImages([])
    } else {
      setUploadedImage(null, null)
    }
    toast.info(mode === 'single' ? '已切换到单图模式' : '已切换到多图模式 (2-4张)')
  }

  // 生成3D模型
  const handleGenerate3D = async () => {
    // 单图模式
    if (generationMode === 'single') {
      const { uploadedImageFile } = useStore.getState()
      
      if (!uploadedImageFile) {
        toast.error('请先上传图片')
        return
      }
      
      console.log('🎬 ========== 单图模式：用户点击生成按钮 ==========')
      console.log('📸 图片文件:', uploadedImageFile.name, '大小:', (uploadedImageFile.size / 1024 / 1024).toFixed(2), 'MB')
      
      // 清除旧的模型数据
      setModelData(null, null)
      console.log('🧹 已清除旧的模型数据')

      try {
        setGenerating(true)
        setCurrentStep(2)
        setUploadStatus('正在上传图片...')
        setGenerationProgress(10)
        
        console.log('🚀 准备调用 Meshy.ai 单图API...')
        console.log('⚙️ 生成设置:', generationSettings)

        // 调用单图API，合并用户设置
        const response = await generate3DModel(uploadedImageFile, {
          quality: 'high',
          format: 'glb',
          ...(generationSettings || {}) // 合并用户自定义设置
        })

        if (response.taskId) {
          setUploadStatus('图片已上传，正在生成3D模型...')
          setGenerationProgress(30)
          
          // 轮询检查生成状态（单图）
          await pollGenerationStatus(response.taskId, 'single')
        }

      } catch (error) {
        handleGenerationError(error)
      }
    }
    // 多图模式
    else if (generationMode === 'multi') {
      if (multiImages.length < 2) {
        toast.error('多图模式至少需要上传2张图片')
        return
      }
      
      if (multiImages.length > 4) {
        toast.error('多图模式最多支持4张图片')
        return
      }
      
      console.log('🎬 ========== 多图模式：用户点击生成按钮 ==========')
      console.log('📸 图片数量:', multiImages.length)
      
      // 清除旧的模型数据
      setModelData(null, null)
      console.log('🧹 已清除旧的模型数据')

      try {
        setGenerating(true)
        setCurrentStep(2)
        setUploadStatus(`正在上传${multiImages.length}张图片...`)
        setGenerationProgress(10)
        
        console.log('🚀 准备调用 Meshy.ai 多图API...')
        console.log('⚙️ 生成设置:', generationSettings)

        // 提取文件数组
        const imageFiles = multiImages.map(img => img.file)

        // 调用多图API，合并用户设置
        const response = await generate3DModelFromMultiImages(imageFiles, {
          quality: 'high',
          format: 'glb',
          ...(generationSettings || {}) // 合并用户自定义设置
        })

        if (response.taskId) {
          setUploadStatus(`${multiImages.length}张图片已上传，正在生成3D模型...`)
          setGenerationProgress(30)
          
          // 轮询检查生成状态（多图）
          await pollGenerationStatus(response.taskId, 'multi')
        }

      } catch (error) {
        handleGenerationError(error)
      }
    }
  }

  // 统一错误处理
  const handleGenerationError = (error) => {
    console.error('3D生成失败:', error)
    
    // 检查是否是付费相关错误
    if (error.message?.includes('免费额度已用完') || error.message?.includes('需要付费')) {
      setShowPaymentModal(true)
    } else {
      toast.error(error.message || '3D模型生成失败，请重试')
    }
    
    setGenerating(false)
    setCurrentStep(1)
    setUploadStatus('')
  }

  // 轮询检查生成状态
  const pollGenerationStatus = async (taskId, mode = 'single') => {
    console.log('🔄 开始轮询任务状态, Task ID:', taskId, '模式:', mode)
    const maxAttempts = 150 // 多图需要更长时间
    let attempts = 0

    const poll = async () => {
      try {
        console.log(`🔍 轮询次数: ${attempts + 1}/${maxAttempts}`)
        
        // 根据模式调用不同的API
        const status = mode === 'multi' 
          ? await checkMultiImageGenerationStatus(taskId)
          : await checkGenerationStatus(taskId)
        console.log('📊 状态响应:', status)
        
        // 更新进度
        if (status.progress !== undefined) {
          // Meshy.ai 的进度是 0-100
          console.log(`📈 进度更新: ${status.progress}%`)
          setGenerationProgress(status.progress)
        }
        
        // 更新状态消息
        if (status.message) {
          console.log(`💬 状态消息: ${status.message}`)
          setUploadStatus(status.message)
        }

        if (status.status === 'completed') {
          console.log('✅ 生成完成！')
          handleGenerationComplete(status)
          return
        } else if (status.status === 'failed') {
          console.error('❌ 生成失败:', status.error)
          throw new Error(status.error || '生成失败，请检查图片质量后重试')
        } else if (status.status === 'processing') {
          attempts++
          if (attempts < maxAttempts) {
            // 根据进度调整轮询频率
            const pollInterval = status.progress > 0 ? 3000 : 5000
            console.log(`⏰ ${pollInterval/1000}秒后再次检查...`)
            setTimeout(poll, pollInterval)
          } else {
            console.error('⏱️ 轮询超时')
            throw new Error('生成超时。Meshy.ai 处理时间较长，请稍后在"我的订单"中查看结果')
          }
        }
      } catch (error) {
        console.error('❌ 检查状态失败:', error)
        toast.error(error.message || '检查生成状态失败')
        setGenerating(false)
        setCurrentStep(1)
        setUploadStatus('')
      }
    }

    poll()
  }

  // 处理生成完成
  const handleGenerationComplete = (data) => {
    setGenerationProgress(100)
    setUploadStatus('🎉 3D模型生成成功！')
    
    // 保存模型数据，使用 GLB 格式
    setModelData(data.modelUrl, {
      ...data,
      id: data.taskId || Date.now().toString(),
      modelUrl: data.modelUrl,
      thumbnailUrl: data.thumbnailUrl,
      videoUrl: data.videoUrl,
      modelUrls: data.modelUrls, // 保存所有格式的 URL
      generatedAt: new Date().toISOString()
    })
    
    setGenerating(false)
    toast.success('✨ 3D模型生成成功！您现在可以 360° 预览并下单了', {
      autoClose: 4000
    })
    
    // 如果有缩略图，显示额外提示
    if (data.thumbnailUrl) {
      console.log('模型缩略图:', data.thumbnailUrl)
    }
    
    setTimeout(() => {
      setUploadStatus('')
    }, 2000)
  }

  return (
    <div className="glass-effect-dark rounded-2xl p-6 border border-white/10 card-hover w-full">
      <div className="flex items-center justify-between mb-6">
        <h2 className="text-2xl font-bold text-white flex items-center space-x-2">
          <span className="text-3xl">📸</span>
          <span>上传产品图片</span>
        </h2>
        
        {/* 模式切换按钮 */}
        <div className="flex items-center space-x-2 bg-white/5 rounded-lg p-1">
          <button
            onClick={() => switchMode('single')}
            disabled={isGenerating}
            className={`px-3 py-1.5 text-sm rounded-md transition-all ${
              generationMode === 'single'
                ? 'bg-accent-purple text-white shadow-md'
                : 'text-gray-400 hover:text-white'
            } ${isGenerating ? 'opacity-50 cursor-not-allowed' : ''}`}
          >
            🖼️ 单图
          </button>
          <button
            onClick={() => switchMode('multi')}
            disabled={isGenerating}
            className={`px-3 py-1.5 text-sm rounded-md transition-all ${
              generationMode === 'multi'
                ? 'bg-accent-blue text-white shadow-md'
                : 'text-gray-400 hover:text-white'
            } ${isGenerating ? 'opacity-50 cursor-not-allowed' : ''}`}
          >
            🎞️ 多图 (2-4张)
          </button>
        </div>
      </div>
      
      {/* 单图模式：已上传图片预览 */}
      {generationMode === 'single' && uploadedImage && (
        <div className="mb-6 relative group">
          <div className="relative rounded-2xl overflow-hidden border-2 border-blue-500/50 shadow-lg shadow-blue-500/20">
            <img 
              src={uploadedImage} 
              alt="已上传" 
              className="w-full h-auto max-h-96 object-contain bg-black/20"
            />
            <div className="absolute top-3 right-3 bg-green-500/90 text-white px-3 py-1.5 rounded-lg text-sm font-semibold flex items-center gap-2 backdrop-blur-sm">
              <svg className="w-4 h-4" fill="currentColor" viewBox="0 0 20 20">
                <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
              </svg>
              已上传
            </div>
          </div>
          <p className="text-center text-sm text-gray-400 mt-3">
            点击下方按钮生成 3D 模型，或 <button onClick={() => setUploadedImage(null, null)} className="text-blue-400 hover:text-blue-300 underline">重新上传</button>
          </p>
        </div>
      )}

      {/* 多图模式：已上传图片预览 */}
      {generationMode === 'multi' && multiImages.length > 0 && (
        <div className="mb-6">
          <div className="flex items-center justify-between mb-3">
            <p className="text-sm text-gray-300">
              已上传 <span className="text-accent-blue font-semibold">{multiImages.length}/4</span> 张图片
            </p>
            {multiImages.length >= 2 && (
              <span className="text-xs text-green-400 flex items-center">
                <svg className="w-3 h-3 mr-1" fill="currentColor" viewBox="0 0 20 20">
                  <path fillRule="evenodd" d="M16.707 5.293a1 1 0 010 1.414l-8 8a1 1 0 01-1.414 0l-4-4a1 1 0 011.414-1.414L8 12.586l7.293-7.293a1 1 0 011.414 0z" clipRule="evenodd" />
                </svg>
                可以生成了
              </span>
            )}
          </div>
          <div className="grid grid-cols-2 md:grid-cols-4 gap-3">
            {multiImages.map((img, index) => (
              <div key={img.id} className="relative group">
                <div className="relative rounded-lg overflow-hidden border-2 border-accent-blue/50 shadow-md aspect-square">
                  <img 
                    src={img.preview} 
                    alt={`图片 ${index + 1}`}
                    className="w-full h-full object-cover"
                  />
                  <div className="absolute top-2 left-2 bg-accent-blue/90 text-white px-2 py-1 rounded text-xs font-semibold">
                    #{index + 1}
                  </div>
                  <button
                    onClick={() => removeMultiImage(img.id)}
                    disabled={isGenerating}
                    className="absolute top-2 right-2 bg-red-500/90 hover:bg-red-600 text-white p-1.5 rounded-full transition-all opacity-0 group-hover:opacity-100 disabled:opacity-50"
                    title="删除"
                  >
                    <svg className="w-3 h-3" fill="currentColor" viewBox="0 0 20 20">
                      <path fillRule="evenodd" d="M4.293 4.293a1 1 0 011.414 0L10 8.586l4.293-4.293a1 1 0 111.414 1.414L11.414 10l4.293 4.293a1 1 0 01-1.414 1.414L10 11.414l-4.293 4.293a1 1 0 01-1.414-1.414L8.586 10 4.293 5.707a1 1 0 010-1.414z" clipRule="evenodd" />
                    </svg>
                  </button>
                </div>
              </div>
            ))}
            {/* 添加更多图片的占位符 */}
            {multiImages.length < 4 && (
              <div className="relative rounded-lg border-2 border-dashed border-white/20 aspect-square flex items-center justify-center text-gray-400">
                <div className="text-center">
                  <svg className="w-8 h-8 mx-auto mb-1 opacity-50" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                  </svg>
                  <p className="text-xs">继续添加</p>
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {/* 单图拖拽上传区域 */}
      {generationMode === 'single' && !uploadedImage && (
        <div
          {...getRootPropsSingle()}
          className={`
            relative border-2 border-dashed rounded-2xl p-8 md:p-12 text-center cursor-pointer
            transition-all duration-300 overflow-hidden group
            ${isDragActiveSingle 
              ? 'border-accent-purple bg-accent-purple/10 scale-105 drag-active shadow-xl shadow-accent-purple/30' 
              : 'border-white/20 hover:border-accent-purple/50 hover:bg-white/5 hover:shadow-lg hover:shadow-accent-purple/20'
            }
            ${isGenerating ? 'opacity-50 pointer-events-none' : ''}
          `}
        >
          <input {...getInputPropsSingle()} />
        
        {/* 背景光效 */}
        <div className="absolute inset-0 bg-gradient-to-br from-accent-purple/5 via-transparent to-accent-blue/5 opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
        
        {/* 动态边框光效 */}
        <div className={`absolute inset-0 rounded-2xl transition-opacity duration-300 ${isDragActiveSingle ? 'opacity-100' : 'opacity-0'}`}>
          <div className="absolute top-0 left-0 w-20 h-20 bg-accent-purple/30 rounded-full blur-2xl"></div>
          <div className="absolute bottom-0 right-0 w-20 h-20 bg-accent-blue/30 rounded-full blur-2xl"></div>
        </div>
        
        <div className="relative space-y-4">
          <div className={`text-5xl md:text-7xl transform transition-all duration-300 ${isDragActiveSingle ? 'scale-125 rotate-12' : 'group-hover:scale-110'}`}>
            {isDragActiveSingle ? '📥' : '📸'}
          </div>
          
          {isDragActiveSingle ? (
            <p className="text-lg md:text-xl text-accent-purple font-bold animate-pulse">
              释放以上传图片 ✨
            </p>
          ) : (
            <>
              <p className="text-base md:text-lg text-white font-semibold">
                拖拽图片到此处，或点击选择文件
              </p>
              <p className="text-xs md:text-sm text-gray-400 flex items-center justify-center flex-wrap gap-2">
                <span className="inline-flex items-center space-x-1">
                  <svg className="w-4 h-4 text-accent-blue" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M4 3a2 2 0 00-2 2v10a2 2 0 002 2h12a2 2 0 002-2V5a2 2 0 00-2-2H4zm12 12H4l4-8 3 6 2-4 3 6z" clipRule="evenodd" />
                  </svg>
                  <span>JPG/PNG/WEBP</span>
                </span>
                <span className="text-gray-500">•</span>
                <span className="inline-flex items-center space-x-1">
                  <svg className="w-4 h-4 text-accent-cyan" fill="currentColor" viewBox="0 0 20 20">
                    <path fillRule="evenodd" d="M3 17a1 1 0 011-1h12a1 1 0 110 2H4a1 1 0 01-1-1zm3.293-7.707a1 1 0 011.414 0L9 10.586V3a1 1 0 112 0v7.586l1.293-1.293a1 1 0 111.414 1.414l-3 3a1 1 0 01-1.414 0l-3-3a1 1 0 010-1.414z" clipRule="evenodd" />
                  </svg>
                  <span>最大 10MB</span>
                </span>
              </p>
            </>
          )}
        </div>
      </div>
      )}

      {/* 多图拖拽上传区域 */}
      {generationMode === 'multi' && (
        <div
          {...getRootPropsMulti()}
          className={`
            relative border-2 border-dashed rounded-2xl p-6 md:p-10 text-center cursor-pointer
            transition-all duration-300 overflow-hidden group
            ${isDragActiveMulti 
              ? 'border-accent-blue bg-accent-blue/10 scale-105 shadow-xl shadow-accent-blue/30' 
              : 'border-white/20 hover:border-accent-blue/50 hover:bg-white/5 hover:shadow-lg hover:shadow-accent-blue/20'
            }
            ${isGenerating || multiImages.length >= 4 ? 'opacity-50 pointer-events-none' : ''}
          `}
        >
          <input {...getInputPropsMulti()} />
        
          {/* 背景光效 */}
          <div className="absolute inset-0 bg-gradient-to-br from-accent-blue/5 via-transparent to-accent-cyan/5 opacity-0 group-hover:opacity-100 transition-opacity duration-500"></div>
        
          <div className="relative space-y-3">
            <div className={`text-4xl md:text-6xl transform transition-all duration-300 ${isDragActiveMulti ? 'scale-125 rotate-12' : 'group-hover:scale-110'}`}>
              {isDragActiveMulti ? '📥' : '🎞️'}
            </div>
          
            {isDragActiveMulti ? (
              <p className="text-lg md:text-xl text-accent-blue font-bold animate-pulse">
                释放以上传图片 ✨
              </p>
            ) : (
              <>
                <p className="text-base md:text-lg text-white font-semibold">
                  {multiImages.length === 0 
                    ? '拖拽2-4张图片到此处，或点击选择' 
                    : `继续添加图片 (${multiImages.length}/4)`
                  }
                </p>
                <p className="text-xs md:text-sm text-gray-400">
                  💡 从不同角度拍摄可获得更精确的3D模型
                </p>
                <p className="text-xs text-gray-500 flex items-center justify-center gap-2">
                  <span>JPG/PNG/WEBP</span>
                  <span>•</span>
                  <span>最大 10MB/张</span>
                </p>
              </>
            )}
          </div>
        </div>
      )}

      {/* 生成设置 - 单图模式 */}
      {generationMode === 'single' && uploadedImage && !isGenerating && (
        <div className="mt-6 animate-scale-in">
          <GenerationSettings 
            mode="single"
            onSettingsChange={setGenerationSettings}
          />
        </div>
      )}

      {/* 生成按钮和进度 - 单图模式 */}
      {generationMode === 'single' && uploadedImage && (
        <div className="mt-6 space-y-4">
          {/* 醒目提示 */}
          {!isGenerating && (
            <div className="flex items-center justify-center gap-3 mb-6 animate-bounce">
              <span className="text-yellow-400 text-2xl animate-pulse">⚡</span>
              <span className="text-base md:text-xl font-black text-transparent bg-clip-text bg-gradient-to-r from-yellow-400 via-orange-400 to-red-400 px-5 py-3 rounded-xl border-2 border-yellow-400/50 shadow-lg shadow-yellow-400/30 animate-pulse">
                点击下方按钮生成 3D 模型
              </span>
              <span className="text-yellow-400 text-2xl animate-pulse">⚡</span>
            </div>
          )}
          
          <button
            onClick={handleGenerate3D}
            disabled={isGenerating}
            className={`
              relative w-full py-5 md:py-7 rounded-2xl font-black text-xl md:text-3xl
              transition-all duration-300 transform overflow-hidden group
              border-2
              ${isGenerating
                ? 'bg-white/10 cursor-not-allowed border-white/20'
                : 'bg-gradient-to-r from-accent-purple via-accent-blue to-accent-cyan text-white hover:scale-105 shadow-2xl shadow-accent-purple/60 hover:shadow-[0_0_50px_rgba(168,85,247,0.8)] border-accent-cyan/50 animate-pulse-glow'
              }
            `}
          >
            {/* 按钮光效 */}
            {!isGenerating && (
              <div className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
            )}
            
            {isGenerating ? (
              <span className="flex items-center justify-center relative z-10">
                <svg className="animate-spin h-5 w-5 md:h-6 md:w-6 mr-2 md:mr-3" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                </svg>
                <span>AI 生成中...</span>
              </span>
            ) : (
              <span className="flex items-center justify-center space-x-3 relative z-10">
                <svg className="w-7 h-7 md:w-9 md:h-9 group-hover:scale-125 group-hover:rotate-12 transition-all duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={3}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span className="group-hover:scale-110 transition-transform duration-300">⚡ 生成你的 3D 模型</span>
                <svg className="w-7 h-7 md:w-9 md:h-9 group-hover:scale-125 group-hover:-rotate-12 transition-all duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={3}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
              </span>
            )}
          </button>

          {/* 进度条 */}
          {isGenerating && (
            <div className="space-y-3 animate-scale-in">
              <div className="relative w-full bg-white/10 rounded-full h-3 md:h-4 overflow-hidden shadow-inner">
                <div 
                  className="absolute inset-0 bg-gradient-to-r from-accent-purple via-accent-blue to-accent-cyan rounded-full transition-all duration-500 ease-out"
                  style={{ width: `${generationProgress}%` }}
                >
                  {/* 进度条光效 */}
                  <div className="absolute inset-0 shimmer"></div>
                  <div className="absolute inset-0 bg-white/20 animate-pulse"></div>
                </div>
                {/* 进度百分比标签 */}
                <div className="absolute inset-0 flex items-center justify-center">
                  <span className="text-xs font-bold text-white drop-shadow-lg">
                    {generationProgress}%
                  </span>
                </div>
              </div>
              <p className="text-xs md:text-sm text-center text-gray-300 font-medium flex items-center justify-center space-x-2">
                <span className="inline-block w-2 h-2 bg-accent-blue rounded-full animate-bounce"></span>
                <span>{uploadStatus}</span>
              </p>
            </div>
          )}
        </div>
      )}

      {/* 生成设置 - 多图模式 */}
      {generationMode === 'multi' && multiImages.length >= 2 && !isGenerating && (
        <div className="mt-6 animate-scale-in">
          <GenerationSettings 
            mode="multi"
            onSettingsChange={setGenerationSettings}
          />
        </div>
      )}

      {/* 生成按钮和进度 - 多图模式 */}
      {generationMode === 'multi' && multiImages.length >= 2 && (
        <div className="mt-6 space-y-4">
          {/* 醒目提示 */}
          {!isGenerating && (
            <div className="flex items-center justify-center gap-3 mb-6 animate-bounce">
              <span className="text-accent-blue text-2xl animate-pulse">🎬</span>
              <span className="text-base md:text-xl font-black text-transparent bg-clip-text bg-gradient-to-r from-blue-400 via-cyan-400 to-teal-400 px-5 py-3 rounded-xl border-2 border-accent-blue/50 shadow-lg shadow-accent-blue/30 animate-pulse">
                多角度生成更精确的 3D 模型
              </span>
              <span className="text-accent-blue text-2xl animate-pulse">🎬</span>
            </div>
          )}
          
          <button
            onClick={handleGenerate3D}
            disabled={isGenerating}
            className={`
              relative w-full py-5 md:py-7 rounded-2xl font-black text-xl md:text-3xl
              transition-all duration-300 transform overflow-hidden group
              border-2
              ${isGenerating
                ? 'bg-white/10 cursor-not-allowed border-white/20'
                : 'bg-gradient-to-r from-accent-blue via-accent-cyan to-teal-400 text-white hover:scale-105 shadow-2xl shadow-accent-blue/60 hover:shadow-[0_0_50px_rgba(59,130,246,0.8)] border-accent-cyan/50 animate-pulse-glow'
              }
            `}
          >
            {!isGenerating && (
              <div className="absolute inset-0 bg-gradient-to-r from-white/0 via-white/20 to-white/0 translate-x-[-100%] group-hover:translate-x-[100%] transition-transform duration-1000"></div>
            )}
            
            {isGenerating ? (
              <span className="flex items-center justify-center relative z-10">
                <svg className="animate-spin h-5 w-5 md:h-6 md:w-6 mr-2 md:mr-3" viewBox="0 0 24 24">
                  <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4" fill="none" />
                  <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z" />
                </svg>
                <span>AI 多图生成中...</span>
              </span>
            ) : (
              <span className="flex items-center justify-center space-x-3 relative z-10">
                <svg className="w-7 h-7 md:w-9 md:h-9 group-hover:scale-125 group-hover:rotate-12 transition-all duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={3}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
                <span className="group-hover:scale-110 transition-transform duration-300">🎬 生成精确 3D 模型 ({multiImages.length}张)</span>
                <svg className="w-7 h-7 md:w-9 md:h-9 group-hover:scale-125 group-hover:-rotate-12 transition-all duration-300" fill="none" stroke="currentColor" viewBox="0 0 24 24" strokeWidth={3}>
                  <path strokeLinecap="round" strokeLinejoin="round" d="M13 10V3L4 14h7v7l9-11h-7z" />
                </svg>
              </span>
            )}
          </button>

          {/* 进度条 */}
          {isGenerating && (
            <div className="space-y-3 animate-scale-in">
              <div className="relative w-full bg-white/10 rounded-full h-3 md:h-4 overflow-hidden shadow-inner">
                <div 
                  className="absolute inset-0 bg-gradient-to-r from-accent-blue via-accent-cyan to-teal-400 rounded-full transition-all duration-500 ease-out"
                  style={{ width: `${generationProgress}%` }}
                >
                  <div className="absolute inset-0 shimmer"></div>
                  <div className="absolute inset-0 bg-white/20 animate-pulse"></div>
                </div>
                <div className="absolute inset-0 flex items-center justify-center">
                  <span className="text-xs font-bold text-white drop-shadow-lg">
                    {generationProgress}%
                  </span>
                </div>
              </div>
              <p className="text-xs md:text-sm text-center text-gray-300 font-medium flex items-center justify-center space-x-2">
                <span className="inline-block w-2 h-2 bg-accent-cyan rounded-full animate-bounce"></span>
                <span>{uploadStatus}</span>
              </p>
            </div>
          )}
        </div>
      )}

      {/* 提示信息 */}
      <div className="mt-6 p-4 bg-accent-blue/10 rounded-xl border border-accent-blue/30 backdrop-blur-sm">
        <p className="text-sm text-gray-300 flex items-start space-x-2">
          <svg className="w-5 h-5 text-accent-blue flex-shrink-0 mt-0.5" fill="currentColor" viewBox="0 0 20 20">
            <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
          </svg>
          <span>
            <strong className="text-white">💡 提示：</strong>为获得最佳效果，请上传清晰、背景简洁的产品图片
          </span>
        </p>
      </div>
      
      {/* 付费提示模态框 */}
      <PaymentRequiredModal 
        isOpen={showPaymentModal}
        onClose={() => setShowPaymentModal(false)}
      />
    </div>
  )
}

